<template>
  <div>
    <edu-dialog :title="(actionType === 'ADD' ? $t('graduationDesign.add'): $t('graduationDesign.edit')) + $t('graduationDesign.studentWhitelist')" width="70%" @close="onCancel" :visible="whitelistDialogVisible">
      <el-form :model="whitelistForm" ref="whitelistForm" :rules="whitelistRules" label-position="right" label-suffix="：" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('graduationDesign.studentNo')" prop="studentId">
              <el-input v-model="whitelistForm.studentId" @blur="handleStudentChange" :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('graduationDesign.studentName')">
              <el-input v-model="whitelistForm.studentName" :placeholder="$t('graduationDesign.pleaseEnter')" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('graduationDesign.college')">
              <el-input v-model="whitelistForm.collegeIdI18n" :placeholder="$t('graduationDesign.pleaseEnter')" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('graduationDesign.major')">
              <el-input v-model="whitelistForm.subjectIdI18n" :placeholder="$t('graduationDesign.pleaseEnter')" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('graduationDesign.direction')">
              <el-input v-model="whitelistForm.directIdI18n" :placeholder="$t('graduationDesign.pleaseEnter')" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <edu-table ref="stuListTable" :data="studentTableData" :selection="false" :order="false" :pagination="false">
        <edu-table-column :label="$t('graduationDesign.subjectCollege')" min-width="110">
          <template slot-scope="scope">
            <el-select v-model="scope.row.optCollegeId" @change="handleCollegeChange($event, scope.row, scope.$index)" filterable clearable class="whitelist-select" :placeholder="$t('graduationDesign.pleaseChoose')">
              <el-option v-for="item in source.collegeOptions" :key="item.collegeId" :label="item.collegeIdI18n" :value="item.collegeId"></el-option>
            </el-select>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('graduationDesign.subjectMajor')" prop="studentId" min-width="110">
          <template slot-scope="scope">
            <el-select v-model="scope.row.optSubjectId" @change="handleSubjectChange($event, scope.row, scope.$index)" filterable clearable class="whitelist-select" :placeholder="$t('graduationDesign.pleaseChoose')">
              <el-option v-for="item in scope.row.subjectOptions" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId"></el-option>
            </el-select>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('graduationDesign.subjectDerection')" prop="studentId" min-width="110">
          <template slot-scope="scope">
            <el-select v-model="scope.row.optDirectId" filterable clearable class="whitelist-select" :placeholder="$t('graduationDesign.pleaseChoose')">
              <el-option v-for="item in scope.row.directionOptions" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('graduationDesign.operation')" prop="studentId" min-width="90">
          <template slot-scope="scope">
            <el-button type="text" @click.stop.prevent="onAdd(scope.row)" v-if="scope.$index === 0">{{$t('graduationDesign.addTo')}}</el-button>
            <el-button type="text" @click.stop.prevent="onDelete(scope.row, scope.$index)" v-else>{{$t('graduationDesign.delete')}}</el-button>
          </template>
        </edu-table-column>
      </edu-table>
      <div slot="buttons">
        <el-button @click="onCancel">{{$t('graduationDesign.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('graduationDesign.confirm')}}</el-button>
      </div>
    </edu-dialog>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/topicWhitelist";
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
  name: 'whitelistDialog',
  props: {
    whitelistDialogVisible: {
      type: Boolean,
      default: false
    },
    actionType: {
      type: String,
      default: ''
    },
    dialogForm: {
      type: Object,
      default: function () {
        return {
          expGradeId: '',
          studentId: '',
          studentName: '',
          collegeIdI18n: '',
          subjectIdI18n: '',
          directIdI18n: ''
        };
      }
    },
    studentTableData: {
      type: Array,
      default: function () {
        return [{
          optCollegeId: '',
          optSubjectId: '',
          optDirectId: '',
          subjectOptions: [],
          directionOptions: []
        }];
      }
    }
  },
  data() {
    return {
      api: API,
      whitelistForm: {
        expGradeId: '',
        studentId: '',
        studentName: '',
        collegeIdI18n: '',
        subjectIdI18n: '',
        directIdI18n: ''
      },
      whitelistRules: {
        studentId: [
          { required: true, message: this.$t('graduationDesign.pleaseEnter'), trigger: 'blur' }
        ]
      },
      source: {
        collegeOptions: []
      },
      deletedData: []
    };
  },
  mounted() {
    this.getCollege();
    this.search();
  },
  methods: {
    async search() {
      this.deletedData = [];
      this.whitelistForm = JSON.parse(JSON.stringify(this.dialogForm));
      if (this.whitelistForm.studentId) {
        this.whitelistForm = await this.getStudentInfo();
      }
      this.formatTopicList();
      this.$nextTick(() => {
        this.$refs.whitelistForm.clearValidate();
      });
    },
    // 课题列表回显
    async formatTopicList() {
      for (let i = 0; i < this.studentTableData.length; i++) {
        const item = this.studentTableData[i];
        // 专业回显
        if (item.optCollegeId && this.whitelistForm.expGradeId) {
          item.subjectOptions = await this.getSubjectList(item.optCollegeId);
          this.studentTableData.splice(i, 1, item);
        }
        // 方向回显
        if (item.optDirectId && item.optSubjectId) {
          item.directionOptions = await this.getDirectionList(item.optSubjectId, item);
          this.studentTableData.splice(i, 1, item);
        }
      }
    },
    // 查学生信息
    getStudentInfo() {
      this.whitelistForm.studentName = "";
      this.whitelistForm.collegeIdI18n = "";
      this.whitelistForm.subjectIdI18n = "";
      this.whitelistForm.directIdI18n = "";
      const params = {
        studentId: this.whitelistForm.studentId
      };
      return this.api.getStudentInfo(params).then(res => {
        return res.data;
      }).catch();
    },
    // 查专业
    getSubjectList(val) {
      const params = {
        grade: this.whitelistForm.expGradeId,
        college: val
      };
      return this.api.getSubject(params).then(res => {
        return this.formatSubjectList(res.data, this.whitelistForm.admissionGrade);
      });
    },
    // 查方向
    getDirectionList(val, row) {
      const admissionGrade = this.findAdmissionGrade(row);
      const params = {
        keyWord: "",
        pageNum_: 1,
        pageSize_: 50,
        grade: admissionGrade,
        professionCode: val
      };
      return this.api.getDirection(params).then(res => {
        return res.data.list;
      });
    },
    // 匹配入学年级
    findAdmissionGrade(row) {
      let subjectIdItem = {};
      if (row.subjectOptions && row.subjectOptions.length) {
        subjectIdItem = row.subjectOptions.find(item => item.subjectId === row.optSubjectId);
      }
      return subjectIdItem && subjectIdItem.admissionGrade ? subjectIdItem.admissionGrade : "";
    },
    // 过滤与学生入学年级相同的专业
    formatSubjectList(data, admissionGrade) {
      let dataset = [];
      data.forEach(item => {
        dataset.push(item);
       /* if (item.admissionGrade === admissionGrade) {
          dataset.push(item);
        }*/
      });
      return dataset;
    },
    // 查学院
    getCollege() {
      tools.initAllCollege(this.source.collegeOptions);
      /*this.api.getCollege().then(res => {
        this.source.collegeOptions = res;
      });*/
    },
    // 选择学院查专业
    handleCollegeChange(val, row, index) {
      row.optSubjectId = "";
      row.subjectOptions = [];
      row.optDirectId = "";
      row.directionOptions = [];
      if (val && this.whitelistForm.expGradeId) {
        const params = {
          grade: this.whitelistForm.expGradeId,
          college: val
        };
        this.api.getSubject(params).then(res => {
          row.subjectOptions = this.formatSubjectList(res.data, this.whitelistForm.admissionGrade);
          this.studentTableData.splice(index, 1, row);
        }).catch();
      }
    },
    // 选择年份和专业查方向
    handleSubjectChange(val, row, index) {
      row.optDirectId = "";
      row.directionOptions = [];
      if (val) {
        const admissionGrade = this.findAdmissionGrade(row);
        const params = {
          keyWord: "",
          pageNum_: 1,
          pageSize_: 50,
          grade: admissionGrade,
          professionCode: val
        };
        this.api.getDirection(params).then(res => {
          row.directionOptions = res.data.list;
          this.studentTableData.splice(index, 1, row);
        }).catch();
      }
    },

    // 输入学生姓名或学号查学生信息
    handleStudentChange() {
      this.whitelistForm.studentName = "";
      this.whitelistForm.collegeIdI18n = "";
      this.whitelistForm.subjectIdI18n = "";
      this.whitelistForm.directIdI18n = "";
      if (this.whitelistForm.studentId) {
        const params = {
          studentId: this.whitelistForm.studentId
        };
        this.api.getStudentInfo(params).then(res => {
          this.whitelistForm = { ...res.data };
        }).catch();
      }
    },
    // 校验白名单列表
    validateWhitelist() {
      let msg = "";
      let valid = true;
      this.studentTableData.forEach(item => {
        if (!item.optCollegeId) {
          msg = this.$t('graduationDesign.subjectCollege');
        } else if (!item.optSubjectId) {
          msg = this.$t('graduationDesign.subjectMajor');
        }
        // else if (item.directionOptions && item.directionOptions.length && !item.optDirectId) {
        //   msg = "课题所属方向";
        // }
      });
      if (msg) {
        this.$message.warning(this.$t('graduationDesign.pleaseChoose') + msg);
        valid = false;
      }
      return valid;
    },
    // 添加
    onAdd(row) {
      if (!this.validateWhitelist()) {
        return false;
      }
      this.studentTableData.push({
        optCollegeId: '',
        optSubjectId: '',
        optDirectId: '',
        subjectOptions: [],
        directionOptions: []
      });
    },
    // 删除
    onDelete(row, index) {
      if (this.actionType === "ADD" || (!row.id && row.id !== 0)) {
        this.studentTableData.splice(index, 1);
      } else if (this.actionType === "EDIT" && (row.id || row.id === 0)) {
        // 编辑时带有id，删除时是软删除
        this.studentTableData.forEach(item => {
          if (row.id === item.id) {
            item.deleteStatus = true;
            this.deletedData.push(item);
            this.studentTableData.splice(index, 1);
          }
        });
      }
    },
    onSubmit() {
      this.$refs.whitelistForm.validate(valid => {
        if (valid) {
          if (!this.validateWhitelist()) {
            return false;
          }
          let data = [];
          let _studentTableData = this.studentTableData.concat(this.deletedData);
          _studentTableData.forEach(item => {
            const _item = Object.assign({}, this.whitelistForm, item);
            data.push(_item);
          });
          this.$emit("whitelist-submit", data, this.actionType);
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.$emit("whitelist-cancel");
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
